// 环境配置文件
// 一般再企业里项目有三个环境
// 开发环境
// 测试环境
// 线上环境
import axios from "axios"
import { getToken } from '@/libs/token.js'
import { ElMessage } from "element-plus";
import router from '@/router/index.js'
const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000
})

//请求拦截
http.interceptors.request.use(request => {
  const token = getToken()
  //const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
  if (token) {
    request.headers = {
      'Content-Type': 'application/json', //配置请求头
      Authorization: 'Bearer ' + token,//配置token
    }
  }
  return request
}, error => {
  return Promise.reject(error)
})
//请求拦截响应
http.interceptors.response.use(response => {
  return response.data
}, error => {
  let { response } = error
  console.log(response)
  const errorInfo = {
    error: true
  }
  if (response) {
    switch (response.status) {
      case 401:
        errorInfo.msg = '令牌失效'
        break;
      case 400:
        errorInfo.msg = '请求错误(400)'
        break;
      case 403:
        errorInfo.msg = '拒绝访问(403)'
        break;
      case 404:
        errorInfo.msg = '请求地址不存在(404)'
        break
      case 500:
        errorInfo.msg = '服务器内部错误（500）'
        break;
      case 502:
        errorInfo.msg = '网关错误(502)'
        break
      case 504:
        errorInfo.msg = '网关超时(504)'
        break
    }
  }
  ElMessage.error(errorInfo.msg)
  return errorInfo
})

export const get = (url, options = null, baseURL = '') => {
  return new Promise((resolve, reject) => {
    http.get(baseURL + url, {
      params: options
    }).then(response => {
      if (response) resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}



export const post = (url, options = false, baseURL = '') => {
  return new Promise((resolve, reject) => {
    http.post(baseURL + url, options).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}
export const $http = {
  get: async (url, data) => {
    try {
      return await http.get(url, { params: data })
    } catch (e) {
      return Promise.reject(e)
    }
  },
  post: async (url, data) => {
    try {
      return await http.post(url, data)
    } catch (e) {
      return Promise.reject(e)
    }
  },
}

export const api = function () {
  //先取开发环境，取不到就默认取生产环境api
  console.log(import.meta.env.VITE_MODE_ENV)
  console.log(import.meta.env.VITE_BASE_URL)
}
